package org.massdeception.content.servlets.authors;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.massdeception.content.entities.MOTD;
import org.massdeception.content.entities.PMF;
import org.massdeception.content.util.SlideUtils;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;

public class AuthorEditMOTDServlet extends AuthorServlet 
{
    private static final Logger log = Logger.getLogger(AuthorEditMOTDServlet.class.getName());
    
    public void process(HttpServletRequest request, HttpServletResponse response, User user)
        throws IOException, ServletException
    {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try
        {            
            String motd = request.getParameter("motd");
            
            if ( motd == null )
                motd = "";
            
            Key key = KeyFactory.createKey(MOTD.class.getSimpleName(), "motd");
            MOTD curMotd = pm.getObjectById(MOTD.class, key);
            curMotd.setMessage(motd);
            
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(SlideUtils.TIMEZONE);
            cal.setTime(new Date());
            int offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000);
            cal.add(Calendar.MINUTE, offset);
            curMotd.setUpdated(cal.getTime());
            curMotd.setUser(user);
            SlideUtils.setMOTD(curMotd);
            
            response.sendRedirect(request.getContextPath()+"/authorSelectSlides");
            
            return;
        }
        catch (Throwable t)
        {
            log.log(Level.WARNING, "Could not query for most current slides", t);
            response.sendError(500, "Request could not be processed.");
            return;
        }
        finally
        {
            pm.close();
        }
    }
}